<?php

namespace App\Http\Controllers;

use App\Models\Member;
use App\Services\QqMiniAppService;
use App\Services\WeChatMiniAppService;
use App\Http\Requests\LoginRequest as Request;
use App\Models\Mplogin;
use App\Services\TtMiniAppService;
use Iamxcd\LaravelCRUD\Traits\HasResponse;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;

class loginController extends Controller
{
    use HasResponse;

    public $app;

    public function __construct(WeChatMiniAppService $wx)
    {
        $this->app = $wx->getApp();
    }

    public function code2token(Request $request)
    {
        $data = $request->validated();
        $key = md5($data['code']);

        if (Cache::get($key, false)) {
            return abort(500, '重复请求');
        }

        Cache::put($key, true, now()->addMinute());

        try {
            if ($request->platform == 'qq') {
                $qq = app(QqMiniAppService::class);
                $response = $qq->code2Session($data['code']);
                $member = Member::query()->firstOrCreate(['openid' => $response['openid']], ['platform' => 'qq']);
            }

            if ($request->platform == 'wx') {
                $wx = app(WeChatMiniAppService::class)->getApp();
                $response = $wx->auth->session($data['code']);
                $member = Member::query()->firstOrCreate(['openid' => $response['openid']], ['platform' => 'wx']);
            }

            if ($request->platform == 'tt') {
                $tt = app(TtMiniAppService::class);
                $response = $tt->code2Session($data['code']);
                $member = Member::query()->firstOrCreate(['openid' => $response['openid']], ['platform' => 'tt']);
            }
        } catch (\Exception $e) {
            throw $e;
            Log::error('登陆', ['msg' => $e->getMessage(), 'Referers' => $request->header('Referer')]);
            return abort(500, '登陆出错');
        }

        return ['token' => $member->createToken($member->id)->plainTextToken];
    }

    public function code2tokenV2(Request $request)
    {
        $data = $request->validated();
        DB::beginTransaction();
        try {
            if ($request->platform == 'qq') {
                $qq = app(QqMiniAppService::class);
                $response = $qq->code2Session($data['code']);
                $member = $this->firstOrCreate($response['openid'], $request->platform);
            }

            if ($request->platform == 'wx') {
                $wx = app(WeChatMiniAppService::class)->getApp();
                $response = $wx->auth->session($data['code']);
                $member = $this->firstOrCreate($response['openid'], $request->platform);
            }

            if ($request->platform == 'tt') {
                $tt = app(TtMiniAppService::class);
                $response = $tt->code2Session($data['code']);
                $member = $this->firstOrCreate($response['openid'], $request->platform);
            }
            DB::commit();
        } catch (\Exception $e) {
            Log::error('登陆', ['msg' => $e->getMessage(), 'Referers' => $request->header('Referer')]);
            DB::rollBack();
            return $this->responseError('登录出错');
        }

        return $this->response([
            'token' => $member->createToken($member->id)->plainTextToken
        ]);
    }

    public function firstOrCreate($openid, $platform)
    {
        $mp = Mplogin::query()->with('user')->where('openid', $openid)->where('platform', $platform)->first();
        if (is_null($mp)) {
            $user = Member::query()->create();
            Mplogin::query()->create([
                'openid' => $openid,
                'platform' => $platform,
                'user_id' => $user->id
            ]);
        } else {
            $user = $mp->user;
            if (is_null($user)) {
                $user = Member::query()->create();
            }
        }
        return $user;
    }

    public function login(Request $request)
    {
        $data = $request->validated();

        $member = Member::query()->where('account', $data['account'])->first();

        if (is_null($member) || !Hash::check($data['password'], $member->password)) {
            return $this->responseError('账户名或密码错误');
        }

        return $this->response([
            'token' => $member->createToken($member->id)->plainTextToken
        ]);
    }

    public function register(Request $request)
    {
        $data = $request->validated();
        Member::query()->create([
            'account' => $data['account'],
            'password' => bcrypt($data['password'])
        ]);
        return $this->responseMessage('注册成功');
    }
}
